package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Transactional
    @Override
    public void save(DishDTO dto) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto,dish);

        //调用mapper层的新增方法
        dishMapper.save(dish);


        //获取dish对象的主键id
        Long dishId = dish.getId();
        log.info("新增完菜品之后返回的主键ID是: {}" , dishId);

        //TODO 新增菜品口味的数据
        List<DishFlavor> flavors = dto.getFlavors();
        //补全集合中的dishID
        if(flavors != null && flavors.size() > 0){
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dishId);
            }
            //向口味表批量插入数据
            dishFlavorMapper.batchInsertion(flavors);
        }


    }

    @Override
    public PageResult page(DishPageQueryDTO dto) {
        //开启分页查询功能
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        //执行查询所有菜品的sql语句  select * from dish
        Page<DishVO> dishList = (Page<DishVO>) dishMapper.page(dto);

        PageResult pageResult = new PageResult(dishList.getTotal(),dishList.getResult());
        return pageResult;
    }

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Override
    public void deleteByIds(List<Long> ids) {// 1,2,3
        //判断当前的的菜品是否能够被删除
        //是否是起售中的菜品  -->  如果是则不能删除,应该返回错误
        for (Long id : ids) {
            Dish dish = dishMapper.getDishById(id);
            if(dish.getStatus() == StatusConstant.ENABLE){
                //当前菜品是起售状态,不能被删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        //是否是被套餐关联了   -->  如果是则不能删除,应该返回错误
        List<Long> setMealIdByDishIds = setmealDishMapper.getSetMealIdByDishIds(ids);
        if(setMealIdByDishIds != null && setMealIdByDishIds.size() > 0){
            //当前菜品是被套餐关联了,不能被删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //删除菜品表中的数据,同时还要把口味表中的数据删除干净
        for (Long id : ids) {
            //删除菜品
            dishMapper.deleteById(id);
            //删除菜品口味数据
            dishFlavorMapper.deleteByDishId(id);
        }
    }

    @Override
    public DishVO getById(Long id) {
        //1,根据传过来的菜品的主键id查询菜品表的数据
        Dish dish = dishMapper.getDishById(id);
        //2,根据传过来的菜品的主键id查询口味表的数据List<DishFlavor>
        List<DishFlavor> dishFlavorList = dishFlavorMapper.getDishFlavorById(id);
        //3,把上两步的返回结果封装到DishVO中
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(dishFlavorList);
        //4,返回DishVo
        return dishVO;
    }

    @Override
    public void update(DishDTO dto) {
        //1,先去修改菜品表的基本信息   20
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto,dish);
        dishMapper.update(dish);
        //2,删除原本的菜品对应口味表的所有数据  dish_id = 20
        dishFlavorMapper.deleteByDishId(dto.getId());
        //3,重新插入新的口味数据
        List<DishFlavor> flavors = dto.getFlavors();
        //补全集合中的dishID
        if(flavors != null && flavors.size() > 0){
            for (DishFlavor flavor : flavors) {
                //dto.getId()就是菜品表的主键
                flavor.setDishId(dto.getId());
            }
            //向口味表批量插入数据
            dishFlavorMapper.batchInsertion(flavors);
        }
    }

    @Autowired
    private SetmealMapper setmealMapper;
    /**
     * 菜品起售停售
     *
     * @param status
     * @param id
     */
    @Transactional
    public void startOrStop(Integer status, Long id) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.update(dish);

        if (status == StatusConstant.DISABLE) {
            // 如果是停售操作，还需要将包含当前菜品的套餐也停售
            List<Long> dishIds = new ArrayList<>();
            dishIds.add(id);
            // select setmeal_id from setmeal_dish where dish_id in (?,?,?)
            List<Long> setmealIds = setmealDishMapper.getSetMealIdByDishIds(dishIds);
            if (setmealIds != null && setmealIds.size() > 0) {
                for (Long setmealId : setmealIds) {
                    Setmeal setmeal = Setmeal.builder()
                            .id(setmealId)
                            .status(StatusConstant.DISABLE)
                            .build();
                    setmealMapper.update(setmeal);
                }
            }
        }
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        // 此list方法在第4天项目实战中已经完成,直接调用即可,没有定义需手动补全.
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getDishFlavorById(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
